/**   
 * @Title: BroadcastRefreshUtil.java 
 * @author 7828wc   
 * @date 2015年9月8日 上午11:05:07 
 */
package com.shanghaionstar.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onstar.cn.api.PublicService;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.mag.publicService.response.BroadcastEntity;
import com.onstar.cn.more.response.BroadcastResponseEntity;
import com.onstar.cn.sqlite.entities.BroadcastHeaderEntity;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.enumtype.OSTypeEnum;
import com.shanghaionstar.sqlite.BroadcastHeaderService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: BroadcastRefreshUtil.java
 * @Description: App launch，LoggedIn，Change Account，Logout refresh boradcast
 *               number
 * @author 7828wc
 * @date 2015年9月8日
 */
public class BroadcastRefreshUtil {
	private Context context;
	private LogManager log;
	private BroadcastHeaderService broadcastService;
	private OnstarApplication onstarApplication;
	private OnResultListener onResultListener;
	private String vin = BroadcastHeaderService.DEFAULTVIN;
	LogManager logger = LogManager.getInstance();

	public BroadcastRefreshUtil(Context context) {
		this.context = context;
		broadcastService = new BroadcastHeaderService(context);
		log = LogManager.getInstance(context);
		onstarApplication = OnstarApplication.getApplication();
	}

	/**
	 * Load broadcast list 
	 */
	@Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO) , method = HttpMethod.PUT)
	public void loadBroadcasts(Context context) {
		if (onstarApplication != null  && !CommonUtil.isNull(ApplicationUtil.getInstance().getVin())) {
			vin = ApplicationUtil.getInstance().getVin();
		} else {
			vin = BroadcastHeaderService.DEFAULTVIN;
		}
		//PublicService service = new PublicService(ConfigUtils.getServerUrl());
		PublicService service = new PublicService(Constants.CURRENT_SERVER_URL);
		RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
		BroadcastEntity broadcastEntity = new BroadcastEntity();
		if (onstarApplication != null && ApplicationUtil.getInstance().getCurrentVehicle() != null) {
			broadcastEntity.setModel(ApplicationUtil.getInstance().getModelDesc());
			broadcastEntity.setVin(ApplicationUtil.getInstance().getVin());
			broadcastEntity.setYear(ApplicationUtil.getInstance().getCurrentVehicle().getYear());
		}
		broadcastEntity.setOsType(OSTypeEnum.ANDROID_SMALL.value());
		requestEntity = service.broadcast(requestEntity, broadcastEntity);

		new Sender().send(requestEntity, new ResponseHandler() {
			@Override
			public void onSuccess(String tag, String json) {
				logger.d("loadBroadcasts===="+json);
				long id = -1;
				if(!json.equals("[]")){ 		//不返回空数组时处理
					List<BroadcastResponseEntity> resultList= new Gson().fromJson(json,new TypeToken<ArrayList<BroadcastResponseEntity>>(){}.getType());
					List<BroadcastHeaderEntity> headers=new ArrayList<BroadcastHeaderEntity>();
					if (resultList != null && resultList.size() > 0) {
						for(BroadcastResponseEntity entity:resultList){
							BroadcastHeaderEntity headerEntity=new BroadcastHeaderEntity();
							headerEntity.setBroadcastId(entity.getId());
							headerEntity.setContent(entity.getContent());
							headerEntity.setCreateDate(new Date().getTime()+"");
							headerEntity.setLanguage(DeviceUtil.getLanguage());
							headerEntity.setModelNumber(entity.getModel());
							headerEntity.setPublishTime(entity.getPublishTimestamp());
							headerEntity.setTitle(entity.getTitle());
							headerEntity.setVin(vin);
							headers.add(headerEntity);
							try {
								String idStr = entity.getId();
								id = Math.max(Long.parseLong(idStr), id);
							} catch (NumberFormatException expected) {
							}
						}
						broadcastService.insert(headers, vin);//添加到数据库
					} else {
						broadcastService.deleteExpireFile(new ArrayList<BroadcastHeaderEntity>(), vin);//删除
					}
				}
				List<BroadcastHeaderEntity> list = broadcastService.getAllBroadcastHeader(vin, FinalConfigParams.FALSE);
				// msg.what = JoinMeConstants.LOAD_BROADCAST_SUCCESS;
				onstarApplication.setBrocastCount(list.size() > 0 ? list.size() >= 99 ? "99" : list.size() + "" : "");
				Message msg = resultHandler.obtainMessage();
				msg.what = FinalConfigParams.SUCCESS;
				msg.obj = id;
				resultHandler.handleMessage(msg);
			}

			@Override
			public void onError(String tag, HttpException e) {
				Message msg = resultHandler.obtainMessage();
				msg.what = FinalConfigParams.ERROR;
				ErrorInfo errorInfo = new ErrorInfo();
//				errorInfo.setCode(e.getErrorCode());
				 errorInfo.setMessageCode(e.getErrorCode());
				errorInfo.setMessageDetail(e.getMessage());
				msg.obj = errorInfo;
				resultHandler.handleMessage(msg);
			}
		}, getClass(), "loadBroadcasts",Context.class);
	}
	/**
	 * Result data processing 
	 */
	private Handler resultHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// super.handleMessage(msg);
			switch (msg.what) {
			case FinalConfigParams.SUCCESS:
					log.d("Get broadcast list success");
					if (onResultListener != null) {
						onResultListener.onResult(msg.what, msg.obj);
				}
				break;
			case FinalConfigParams.ERROR:
				log.d("Get broadcast list error.see the details.");
				if (onResultListener != null) {
					onResultListener.onResult(msg.what, msg.obj);
				}else{
					ErrorInfo errorInfo=(ErrorInfo) msg.obj;
//					AlertDialogUtil.showAlertDialog(context, "", errorInfo.getMessageDetail());
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * Set get data refresh listener 
	 * @param onResultListener
	 */
	public void setOnResultListener(OnResultListener onResultListener) {
		this.onResultListener = onResultListener;
		log.d("set result listener.");
	}



	/**
	 * Call back refresh listener
	 * @author 7828wc
	 *
	 */
	public interface OnResultListener {
		void onResult(int code, Object obj);
	}
}
